package com.tintintech.sendmail;

import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

import com.tintintech.commons.querystring.NameValueNode;
import com.tintintech.monkey.Session;
import com.tintintech.monkey.SimpleHandler;
import com.tintintech.monkey.codec.scgi.SCGIDecoder.SCGIStruct;

import com.tintintech.sendmail.helper.DataHelper;
import com.tintintech.sendmail.util.MailStore;
import com.tintintech.sendmail.util.MailStat;
import com.tintintech.sendmail.util.PrimaryKey;
import com.tintintech.sendmail.util.Reload;
import com.tintintech.sendmail.util.Reset;

public class MailHandler extends SimpleHandler{

    @Override
    public void onMessageReceived(final Session session)
    {
        final SCGIStruct struct = (SCGIStruct) session.getDecoderOutput();
        final NameValueNode params = struct.getParameters();
        final String command = params.get("command").getValue();
        if (command.equals("sendmail")){
            try {
                String body = new String(struct.getInput().buf(), struct.getBdStart(), struct.getBdLen(), "UTF-8");
                
                List<Map<String, String>> items = DataHelper.JSON.decodeForList(body);
                int total = items.size(), i = 0;
                try {
                    DataHelper.DB.open(MailStore.DB_NAME);
                    for (; i < total; i++)
                    {
                        Map<String, String> map = items.get(i);            
                        DataHelper.DB.put(PrimaryKey.UUID(), DataHelper.JSON.encode(map));
                        MailStat.RECV_SUCCESS_NUM.incrementAndGet();
                    }
                    DataHelper.DB.sync();
                    DataHelper.DB.dbClose();
                } catch (Throwable e) {
                	System.out.println("recv-data-err");
                }
                session.getOutput().write("total: " + i + "\n");
            } catch (UnsupportedEncodingException e) {
                System.out.println("recv mailbox error!");
            }            
        } else if (command.equals("status")) {
            
            /* 已发送邮件数量，未发送邮件数量，发送失败的邮件数量, 总共接收到的邮件数 */
        	session.getOutput().write(MailStat.getData());
        } else if (command.equals("reset")) {
            Reset.mailBox();
            session.getOutput().write("reset ok!");
        } else if (command.equals("reload")) {
        	/* @todo: 未完成测试 */
        	Reload.run();
        	session.getOutput().write("reload ok!");
        }
        /*
         * 接口参数
         * 1. 获取状态的指令
         * 2. 复位，系统初始化 
         * 3. 接收数据
         */

    }
}
